package com.jsmile.cloud.authc.web.config;

import java.util.ArrayList;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.store.redis.RedisTokenStore;

import com.google.common.collect.Lists;
import com.jsmile.cloud.authc.web.security.provider.SsoAuthProvider;
import com.jsmile.mall.api.constants.JSmileConstant;

import lombok.AllArgsConstructor;

/**
 * 认证服务
 *
 * @author Morily
 */
@Configuration
@EnableAuthorizationServer
@AllArgsConstructor
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    private final RedisConnectionFactory redisConnectionFactory;
    private final UserDetailsService jsmileUserService;

    @Bean
    public RedisTokenStore tokenStore() {
        return new RedisTokenStore(redisConnectionFactory);
    }

    @Bean
    public SsoAuthProvider ssoAuthProvider() {
        return new SsoAuthProvider();
    }

    @Bean
    public AuthenticationManager authenticationManager() {
        ArrayList<AuthenticationProvider> list = Lists.newArrayList();
        list.add(ssoAuthProvider());
        return new ProviderManager(list);
    }

    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
        endpoints.authenticationManager(authenticationManager()).userDetailsService(jsmileUserService)// 若无，refresh_token会有UserDetailsService is required错误
            .tokenStore(tokenStore());
    }

    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) throws Exception {
        // 允许表单认证
        security.allowFormAuthenticationForClients().tokenKeyAccess("permitAll()").checkTokenAccess("isAuthenticated()");
    }

    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.inMemory().withClient(JSmileConstant.PASSWORD.client_id).secret(new BCryptPasswordEncoder().encode(JSmileConstant.PASSWORD.client_secret)).scopes("all")
            .accessTokenValiditySeconds(3600 * 24 * 7) // 7 天
            .refreshTokenValiditySeconds(2592000 * 3) // 30 days
            // 客户端模式
            .authorizedGrantTypes("authorization_code", "password", "refresh_token", "client_credentials").and().withClient("jsmile-cloud")
            // 权限范围
            .scopes("jsmile-cloud").authorizedGrantTypes("implicit");
    }
}
